package com.jing.cloud.zookeeper;

import org.apache.curator.RetryPolicy;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.jing.cloud.util.PropertiesUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.springframework.stereotype.Service;

import java.util.Map;


@Service
public class ZookeeperHelp {

    private final static Logger logger = LoggerFactory.getLogger(ZookeeperHelp.class);
    private int zookeeperTimeOut = 30 * 1000;
    private CuratorFramework client;
    private String PATH = "/linkdood/";

    private void connect() {
        CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder();
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        client = builder.connectString(PropertiesUtil.getProperties("zookeeperAddress"))
                .connectionTimeoutMs(this.zookeeperTimeOut).sessionTimeoutMs(zookeeperTimeOut).retryPolicy(retryPolicy).build();
        client.start();
    }


    public void setConfig(Map<String, String> config) {
        if (!config.isEmpty()) {
            connect();
            for (String key : config.keySet()) {
                if (StringUtils.isNotBlank(config.get(key))) {
                    try {
                        Stat stat = client.checkExists().forPath(PATH + key);
                        if (stat == null) {
                            client.create().creatingParentContainersIfNeeded().withMode(CreateMode.PERSISTENT).forPath(PATH + key, config.get(key).getBytes());
                        } else {
                            client.setData().forPath(PATH + key, config.get(key).getBytes());
                        }
                    } catch (Exception e) {
                        logger.error("setData error", e);
                    }
                }

            }
        }

    }

    public String getData(String configName) {
        try {
            Stat stat = new Stat();
            byte[] bytes = client.getData().storingStatIn(stat).forPath(PATH+configName);
            if (bytes.length > 0) {
                return new String(bytes);
            }
        } catch (Exception e) {
            logger.error("getData error", e);
        }
        return "";
    }

    public void delete(String path){
        try {
            client.delete().deletingChildrenIfNeeded().forPath(path);
        } catch (Exception e) {
            logger.error("delete error", e);
        }
    }


}
